package com.asiainfo.kbisheet.model
{
	import com.asiainfo.kbisheet.common.Util;
	import com.asiainfo.kbisheet.components.condition.ConditionInput;
	import com.asiainfo.kbisheet.components.condition.ConditionItem;
	import com.asiainfo.kbisheet.control.MessageControl;
	import com.asiainfo.kbisheet.vo.ColumnVO;
	import com.asiainfo.kbisheet.vo.KbsSheetVO;
	import com.asiainfo.kbisheet.vo.QueryVO;
	import com.asiainfo.kbisheet.vo.SettingVO;
	import com.asiainfo.kbisheet.vo.WhereVO;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	
	[Event(name="updateHiddenColumnUUIDs", type="mx.events.Event")]
	
	/**
	 * 核心的表单模型，存储大部分与报表相关的信息。
	 * 
	 */
	[Bindable]
	public class KbsModel extends EventDispatcher
	{
		private static var _instance:KbsModel;
		
		public static function getInstance():KbsModel{
			if(_instance == null){
				_instance = new KbsModel();
			}
			return _instance;
		}
		
		protected var messageControl:MessageControl = new MessageControl();
		
		/**解码后的真实用户ID*/
		public var userId:String;
		
		/**表单ID*/
		public var sid:String;
		
		/** KbsSheetVO 对象*/
		public var kbsSheetVO:KbsSheetVO;
		
		/** ColumnVO的集合 */
		public var columns:ArrayCollection;
		
		/** 表单定义的XML文本内容 */
		private var _sheetXML:XML;	
		
		public var sql:String;
		
		public var order:String;
		
		/** 是否可分页 */
		public var pageable:Boolean;
		
		/** 每页记录数 */
		public var countPerPage:int;
		
		/** 最大记录数 */
		public var maxCount:int;
		
		/** 当前页 */
		public var currentPage:int;
		
		/** 最大页 */
		public var maxPage:int;
		
		/** 条件XML */
		public var conditionsXML:XML;
		
		/** 列XML */
		public var columnsXML:XML;
		
		/**公告链接配置的XML*/
		public var linksXML:XML;
		
		/** ConditionItem的集合 */
		public var conditionItemHandler:ArrayCollection = new ArrayCollection();
		
		/** 查询交互VO */
		public var queryVO:QueryVO;
		
		/** 保存水平滚动条位置 */
		public var horizontalScrollPosition:Number;
		
		/** 显示列  */
		public var groupedColumns:Array;
		
		/** 设置列(树形结构) */
		public var userSetColumns:Array;
		
		/** 隐藏列(平面结构) */
		public var hiddenColumnUUIDs:ArrayCollection;
		
		/** 是否可导出为Excel*/
		public var enableExport:Boolean;
		
		/** 是否可全部导出 */
		public var enableExportAll:Boolean;
		
		/** 全部导出的库名 */
		public var exportAllDataBase:String;
		
		/** 全部导出的表名 */
		public var exportAllTable:String;
		
		/** 排序方向 */
		public var remoteOrderByDirection:String ='';
		
		/** 是否有页面外链接 */
		public var enableLink:Boolean;
		
		/** 页面外链接标签 */
		public var linkLabel:String;
		
		/** 页面外链接地址 */
		public var linkURL:String;
		
		/** 备注文本 */
		public var remarkTextFlowXML:XML;
		
		/** 备注高度 */
		public var remarkHeight:int;
		
		/** 显示备注 */
		public var showRemark:Boolean;
		
		protected function updateMessage(message:String):void{
			messageControl.updateMessage(message);
		}
		
		public function updateHiddenColumnUUIDs(value:ArrayCollection):void{
			hiddenColumnUUIDs = value;
			var newEvent:Event = new Event("updateHiddenColumnUUIDs");
			dispatchEvent(newEvent);
		}		
		
		public function get sheetXML():XML{
			return _sheetXML;
		}
		
		private function getDefaultOrder():String{
			var defaultOrder:String = "";
			if(SettingModel.getInstance().settingVO != null){			
				for each(var dimColumn:String in SettingModel.getInstance().settingVO.dimColumns){
					for each(var columnXML:XML in _sheetXML.columns..column){
						var name:String = columnXML.@name;
						if(name.length > 0){
							if(dimColumn.lastIndexOf(name) == 0){
								defaultOrder = defaultOrder + dimColumn + ","
							}
						}
					}
				}
				defaultOrder = defaultOrder.substr(0,defaultOrder.length - 1);
			}
			return defaultOrder;
		}
		
		public function set sheetXML(value:XML):void{
			_sheetXML = value;
			
			kbsSheetVO.databaseName = Util.getModeElement(_sheetXML,'databaseName');
			kbsSheetVO.tableName = Util.getModeElement(_sheetXML,'tableName');
			sql = Util.getModeElement(_sheetXML, 'sql');
			
			
			if(_sheetXML.hasOwnProperty('links')){
				linksXML = XML(_sheetXML.links);
			}
			
			if(_sheetXML.hasOwnProperty('conditions')){
				conditionsXML = XML(_sheetXML.conditions);
			}
			columnsXML = XML(_sheetXML.columns);
			
			/*排序*/
			if(_sheetXML.hasOwnProperty('order')){
				order = _sheetXML.order;
			}
			else{
				order = getDefaultOrder();
			}
			
			/*判断导出功能*/
			if(_sheetXML.hasOwnProperty('export')){
				var exportXML:XML = XML(_sheetXML.export);
				/*导出为Excel*/
				if(exportXML.hasOwnProperty('@enable')){
					enableExport =(exportXML.@enable == 'true');
				}
				
				if(exportXML.hasOwnProperty('@enableAll')){
					enableExportAll = (exportXML.@enableAll == 'true');
				}
				
				if(exportXML.hasOwnProperty('@exportAllDataBase')){
					exportAllDataBase = exportXML.@exportAllDataBase;
				}
				
				if(exportXML.hasOwnProperty('@exportAllTable')){
					exportAllTable = exportXML.@exportAllTable;
				}
			}
			
			/*分页设置*/
			if(_sheetXML.hasOwnProperty('paginate')){
				if(_sheetXML.paginate.hasOwnProperty('@countPerPage')){
					countPerPage = int(_sheetXML.paginate.@countPerPage);
				}			
				
				if(_sheetXML.paginate.hasOwnProperty('@pageable') && _sheetXML.paginate.@pageable == 'true'){
					pageable = true;
				}				
			}
			else{
				countPerPage = 100;
			}
			
			/*计算columns*/
			columns = new ArrayCollection();
			//trace("length:" + _sheetXML.columns..column.length());
			for each(var columnXML:XML in _sheetXML.columns..column){
				var name:String = columnXML.@name;
				if(name.length > 0){
					var columnVO:ColumnVO = new ColumnVO();
					columnVO.name = columnXML.@name;
					columnVO.title = columnXML.@title;
					columnVO.longTitle = columnXML.@longTitle;
					columnVO.type = columnXML.@type;
					if(columnXML.hasOwnProperty('@sql')){
						columnVO.sql = columnXML.@sql;
					}
					columns.addItem(columnVO);
				}					
			}
			
			/*分析外链接*/
			if(_sheetXML.hasOwnProperty('link')){
				var linkXML:XML = XML(_sheetXML.link);
				if(linkXML.hasOwnProperty('@label') && linkXML.hasOwnProperty('@url')){
					enableLink =true;
					linkLabel = linkXML.@label;
					linkURL = linkXML.@url;
				} 
			}
			
			/*备注*/
			if(_sheetXML.hasOwnProperty('remark')){
				showRemark = true;
				remarkTextFlowXML = <TextFlow xmlns="http://ns.adobe.com/textLayout/2008" whiteSpaceCollapse="preserve"/>;
				remarkTextFlowXML.appendChild(_sheetXML.remark.*);
				remarkHeight = 100;
				if(_sheetXML.remark.hasOwnProperty('@height')){
					remarkHeight = int(_sheetXML.remark.@height);
				}
			}			
		}
		
		/**
		 * 通过Id查找ConditionItem对象
		 */
		public function getConditionItemById(id:String):ConditionItem{
			for each(var item:ConditionItem in conditionItemHandler){
				if(item.conditionId == id){
					return item;
				}
			}
			return null;
		}
		
		/**
		 * 通过列名查找ConditionItem对象
		 */
		public function getConditionItemByColumn(column:String):ConditionItem{
			for each(var item:ConditionItem in conditionItemHandler){
				if(item.column == column){
					return item;
				}
			}
			return null;
		}
		
		public function getConditionItemWheresByColumn(column:String):ArrayCollection{
			var conditionItem:ConditionItem = getConditionItemByColumn(column);
			if(conditionItem){
				return conditionItem.getWheres();
			}
			return null;
		}
		
		public function getConditionItemValueByColumn(column:String):String{
			var conditionItem:ConditionItem = getConditionItemByColumn(column);
			if(conditionItem){
				return conditionItem.getAValue();
			}
			return null;
		}
		
		
		public function getConditionItemWheresById(id:String):ArrayCollection{
			var conditionItem:ConditionItem = getConditionItemById(id);
			updateMessage("KbsModel:getConditionItemWheresById():得到ConditionItem：" + id);
			if(conditionItem){
				return conditionItem.getWheres();
			}
			return null;
		}
		
		public function getConditionItemValueById(id:String):String{
			var conditionItem:ConditionItem = getConditionItemById(id);
			if(conditionItem != null){
				updateMessage("KbsModel:getConditionItemValueById():得到wheres：" + id);
				return conditionItem.getValue();
			}
			return null;
		}
		
		/**
		 * 判断一组条件XML是否为trues
		 */
		public function isIfsTrue(ifsXMLList:XMLList, linkSign:String = "and"):Boolean{
			for each(var xml:XML in ifsXMLList){
				var isTrue:Boolean = true; 
				
				if(xml.name() == "if"){
					isTrue = isIfTrue(xml);
				}
				else if(xml.name() == "and"){
					isTrue = isIfsTrue(xml.children(), "and");
				}
				else if(xml.name() == "or"){
					isTrue = isIfsTrue(xml.children(), "or");
				}
				else {
					isTrue = isIfsTrue(xml.children(), linkSign);
				}
				
				if(linkSign=="and" && isTrue == false){
					//trace(false+ifsXMLList.toXMLString());
					return false;
				}
				
				if(linkSign=="or" && isTrue == true){
					//trace(true+ifsXMLList.toXMLString());
					return true;
				}
				
			}
			
			if(linkSign=="or"){
				//trace(false+ifsXMLList.toXMLString());
				return false;
			}
			//trace(true+ifsXMLList.toXMLString());
			return true;
		}
		
		private function getConditionItemValue(ifXML:XML):String{
			var conditionItemValue:String = null;
			if(ifXML.hasOwnProperty('@conditionId')){
				conditionItemValue = getConditionItemValueById(ifXML.@conditionId);
			}
			else if(ifXML.hasOwnProperty('@column')){
				conditionItemValue = getConditionItemValueByColumn(ifXML.@column);
			}
			
			return conditionItemValue;
		}
		
		private function isIfTrue(ifXML:XML):Boolean{			
			var equal:String = ifXML.@equal;
			var value:String = ifXML.@value;			
			var conditionItemValue:String = getConditionItemValue(ifXML);
			if(!isLinkedConditionItemTrue(equal,conditionItemValue,value)){
				return false;
			}
			
			return true;
		}
		
		/*判断关联输入框的值是否满足条件*/
		private function isLinkedConditionItemTrue(equal:String,conditionItemValue:String,value:String):Boolean{
			if(value!=null && value.length==0){
				value= null;
			}			
			
			if(equal=="e" && (conditionItemValue == value)){
				//trace(true+ " : "+value + " " + equal + " (conditionInputValue)" + conditionInputValue);
				return true;
			}
			
			if(equal=="ne" && (conditionItemValue != value)){
				//trace(true+ " : "+value + " " + equal + " (conditionInputValue)" + conditionInputValue);
				return true;
			}
			//trace(false+ " : "+value + " " + equal + " (conditionInputValue)" + conditionInputValue);
			return false;
		}
		
		/*收集要排除的设置*/
		public function getExcludes():ArrayCollection{			
			var excludes:ArrayCollection = new ArrayCollection();
			for each(var excludeItem:ConditionItem in conditionItemHandler){
				var excludeXMLList:XMLList = excludeItem.getExcludes();
				if(excludeXMLList != null){
					for each(var excludeXML:XML in excludeXMLList){
						excludes.addItem(excludeXML);
					}						
				}
			}
			return excludes;
		}
		
		/*收集要附加的设置*/
		public function getIncludes():ArrayCollection{				
			var includes:ArrayCollection = new ArrayCollection();
			for each(var includeItem:ConditionItem in conditionItemHandler){
				var includeXMLList:XMLList = includeItem.getIncludes();
				if(includeXMLList != null){
					for each(var includeXML:XML in includeXMLList){
						includes.addItem(includeXML);
					}						
				}
			}
			return includes;
		}
		
		/*判断一个条件是否被排除*/
		private function isExcluded(conditionItem:ConditionItem, excludes:ArrayCollection):Boolean{
			for each(var excludeXML:XML in excludes){
				if(excludeXML.@conditionId == conditionItem.conditionId){
					if(isLinkedConditionItemTrue(excludeXML.@equal,conditionItem.getAValue(),excludeXML.@value)){
						return true;
					}
				}
			}
			return false;
		}
		
		/**获取WhereVO集合*/
		public function getWheres():ArrayCollection{
			/*收集要排除的设置*/
			var excludes:ArrayCollection = getExcludes();
			
			var wheres:ArrayCollection = new ArrayCollection();
			for each(var item:ConditionItem in conditionItemHandler){
				var itemWheres:ArrayCollection = item.getWheres();
				if(itemWheres != null){
					if(!isExcluded(item,excludes)){
						Util.addAll(wheres,itemWheres);
					}
				}
			}
			
			/*收集要附加的设置*/
			var includes:ArrayCollection = getIncludes();
			//trace("includes length:"+includes.length);
			for each(var includeXML:XML in includes){
				var whereVO:WhereVO = new WhereVO();
				whereVO.column = includeXML.@column;
				whereVO.equalSign = "=";
				if(includeXML.hasOwnProperty('@equal')){
					var equal:String = includeXML.@equal;
					if(equal == 'ne'){
						whereVO.equalSign = "<>";
					}
				}
				whereVO.value = includeXML.@value;
				wheres.addItem(whereVO);
			}
			
			return wheres;
			
		}	
		
		public function getLink(id:String):XML{
			return XML(linksXML.link.(hasOwnProperty('@id') && @id == id));
		}		
	}
}